package com.zxl.manager.privacy.utils.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/7/5.
 */
public class HttpUtils {

    public static byte[] doGet(String url, Map<String, String> params) {
        StringBuilder requestURL = new StringBuilder();
        requestURL.append(url);
        int size = params.size();
        if (null != params && !params.isEmpty()) {
            requestURL.append("?");
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) {
                try {
                    String key = iterator.next();
                    String value = params.get(key);
                    value = value == null ? "" : value;
                    requestURL.append(URLEncoder.encode(key, "utf-8"));
                    requestURL.append("=");
                    requestURL.append(URLEncoder.encode(value, "utf-8"));
                    requestURL.append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            requestURL.deleteCharAt(requestURL.length() - 1);
        }
        return doGet(requestURL.toString());
    }

    public static byte[] doGet(String url) {
        try {
            LogUtils.d("url : " + url);
            Response response = new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute();
            if (response.isSuccessful() && !response.isRedirect()) {
                return response.body().bytes();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void doGet(String url, Callback callback) {
        new OkHttpClient().newCall(new Request.Builder().url(url).build()).enqueue(callback);
    }
}
